import React, { useState, useCallback, useMemo, memo, useEffect } from 'react';
import { DatePicker, Button, Icon, Menu, Form, message, Dropdown, Select, Modal } from 'antd';
import moment from 'moment';

import { download } from '@/utils/utils';
import If from '@/components/If';
import BizIcon from '@/components/BizIcon';
import OrganizationSelect from '@/components/OrganizationSelect';
import { queryDictList, salaryRecheck } from '@/services/salaryManage/salaryCalculate';

import { BUTTON } from '@/pages/SalaryManage/SalaryCalculate/constant/recheckButtonConstant';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import Search from '@/pages/SalaryManage/components/SuperSearch';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import { goToProcessApply, goToProcessDetail } from '@/pages/SalaryManage/utils/pageNavigateUtil';
import { PROCESS_TYPE } from '@/pages/SalaryManage/utils/processUtil';
import BaseMore from './baseMore';
import styles from './index.less';

const { MonthPicker } = DatePicker;
const { confirm } = Modal;

const CheckHeader = props => {
    const {
        period,
        dispatch,
        dispatchType = {},
        selectedRows,
        checkButtonList,
        searchModel,
        organizationList,
        form
    } = props;
    const { organizationCode, departmentCode } = searchModel
    const {
        initType,
        searchType,
        // confirmItemRecheckType,
        // approveSubmitType,
        sendSalaryPayrollInit,
        applyPaymentType,
        passCheckBatchType,
        rejectInitType,
        updateDataType,
        postponeNextMonthType,
        excelExportType
    } = dispatchType;
    const { getFieldDecorator } = form;

    const [financeCheckList, setFinanceCheckList] = useState([]);
    const [hrCheckList, setHrCheckList] = useState([]);

    const getDictList = async () => {
        try {
            const { code, data = {} } = await queryDictList('financeCheckStatusEnum,hrCheckStatusEnum');
            if (code === 10000) {
                setFinanceCheckList(data.financeCheckStatusEnum);
                setHrCheckList(data.hrCheckStatusEnum);
            }
        } catch (e) {
            console.log(e);
        }
    };

    useEffect(() => {
        getDictList();
    }, []);

    const onChange = (date, dateString) => {
        dispatch({
            type: dispatchType.sharedState,
            payload: {
                sharePeriod: dateString
            },
            callback() {
                dispatch({
                    type: initType,
                    payload: dateString
                });
            }
        })
    };

    // const [, setVisible] = useState(false);

    const getRightButton = useCallback(code => (checkButtonList || []).find(item => item.code === code), [
        checkButtonList
    ]);

    // 是否需要显示按钮
    const needShowButton = useCallback(
        code => {
            const matchButton = getRightButton(code);
            return matchButton && !matchButton.disabled;
        },
        [getRightButton]
    );

    const HasRight = useCallback(({ code, children }) => (needShowButton(code) ? children : null), [needShowButton]);

    // 提交审批流
    const approveSubmit = async () => {
        // dispatch({
        //     type: approveSubmitType,
        //     payload: {},
        //     callback: response => {
        //         message[response.code === 10000 ? 'info' : 'warn'](response.msg);
        //     }
        // });
        Modal.confirm({
            title: '确定提交薪资审批？',
            centered: true,
            onOk: async () => {
                const {
                    contrastType = 1,
                    downAbnormalTipIndex,
                    upAbnormalTipIndex,
                    salaryRateKpiInd = 1
                } = searchModel;
                try {
                    await salaryRecheck
                        .saveApproveBusinessData({
                            year: period.substr(0, 4),
                            month: period.substr(5),
                            contrastType,
                            downAbnormalTipIndex,
                            upAbnormalTipIndex,
                            salaryRateKpiInd,
                            organizationCode
                        })
                        .then(res => {
                            goToProcessApply(
                                PROCESS_TYPE.SALARY_RECHECK_APPLY,
                                { contrastType, period, organizationCode, salaryPayrollProcessRecordId: res.data },
                                '没有找到分类为【财务薪资复核审批流程】的流程，请先配置流程'
                            );
                        });
                } catch (error) {
                    message.warn('提交失败');
                }
            }
        });
    };

    // 下发薪资单
    const sendSalaryPayroll = useCallback(() => {
        if (selectedRows && selectedRows.length > 0) {
            message.warn('下发薪资单为全量行为，请直接点击按钮');
            return;
        }
        dispatch({
            type: sendSalaryPayrollInit,
            payload: true
        });
    }, [selectedRows]);

    // 申请付款
    const applyPayment = useCallback(() => {
        if (selectedRows && selectedRows.length > 0) {
            message.warn('申请付款为全量行为，请直接点击按钮');
            return;
        }
        dispatch({
            type: applyPaymentType,
            callback: response => {
                message[response.code === 10000 ? 'success' : 'warn'](response.msg);
            }
        });
    }, [selectedRows]);

    // 批量复核通过
    const batchApprove = useCallback(() => {
        if (!selectedRows || selectedRows.length === 0) {
            message.warn('请选择批量通过的对象');
            return;
        }
        confirm({
            title: '批量确认',
            content: '确认要批量通过员工的薪资信息吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            icon: <Icon type="exclamation-circle" theme="filled" />,
            onOk() {
                dispatch({
                    type: passCheckBatchType,
                    payload: selectedRows,
                    callback: response => {
                        message[response.code === 10000 ? 'success' : 'warn'](response.msg);
                    }
                });
            },
            onCancel() {
                console.log('Cancel');
            }
        });
    }, [selectedRows]);

    // 批量驳回
    const batchReject = useCallback(() => {
        if (selectedRows && selectedRows.length > 0) {
            message.warn('驳回为全量行为，请直接点击按钮');
            return;
        }
        dispatch({
            type: rejectInitType,
            payload: {
                visible: true
            }
        });
    }, [selectedRows]);

    // 更新数据
    const updateData = useCallback(() => {
        dispatch({
            type: updateDataType,
            payload: selectedRows,
            callback: response => {
                if (response.code === 10000) {
                    message.success(response.msg)
                }
            }
        });
    }, [selectedRows]);

    const goToSubmitDetail = () => {
        const submitButton = getRightButton(BUTTON.FN_SUBMIT_DETAIL);
        goToProcessDetail(submitButton.butQueryParamVO);
    }

    // 推迟下月发放
    const postponeNextMonth = useCallback(() => {
        if (!selectedRows || selectedRows.length === 0) {
            message.warn('请选择推迟下月发放的对象');
            return;
        }
        dispatch({
            type: postponeNextMonthType,
            payload: selectedRows,
            callback: response => {
                if (response.code === 10000) {
                    message.success(response.msg)
                }
            }
        });
    }, [selectedRows]);

    // excel导出
    const excelExport = () => {
        download({
            getData: () => dispatch({ type: excelExportType })
        });
    };

    const handleOrgChange = val => {
        dispatch({
            type: dispatchType.sharedState,
            payload: {
                shareOrganizationCode: val,
                sharePeriod: undefined
            },
            callback() {
                dispatch({
                    type: dispatchType.searchCondition,
                    payload: {
                        organizationCode: val
                    },
                    callback() {
                        dispatch({
                            type: dispatchType.initType
                        });
                    }
                });
            }
        })
    }

    const handleDepChange = val => {
        dispatch({
            type: dispatchType.searchCondition,
            payload: {
                departmentCode: val
            },
            callback() {
                dispatch({
                    type: dispatchType.searchType
                });
            }
        });
    }

    const searchHandle = () => {
        const { hireDate, ...searchValue } = form.getFieldsValue();
        dispatch({
            type: searchType,
            payload: {
                ...searchValue,
                hireDate,
                hireDateBegin: hireDate?.[0] ? hireDate[0].format('YYYY-MM-DD') : null,
                hireDateEnd: hireDate?.[1] ? hireDate[1].format('YYYY-MM-DD') : null
            }
        });
    };

    // 1.设置默认选择月份
    const periodMoment = period ? moment(period) : null;

    const dropDownMenu = useMemo(() => {
        const dropMenu = [];

        // if (needShowButton(BUTTON.UPDATE_DATA) || needShowButton(BUTTON.FN_UPDATE_DATA)) {
        //     dropMenu.push(
        //         <Menu.Item key={BUTTON.UPDATE_DATA} onClick={updateData}>
        //             更新数据
        //         </Menu.Item>
        //     );
        // }

        // dropMenu.push(
        //     <Menu.Item key="2" onClick={postponeNextMonth} disabled>
        //         推迟下月发放
        //     </Menu.Item>
        // );

        if (needShowButton(BUTTON.EXCEL_EXPORT) || needShowButton(BUTTON.FN_EXCEL_EXPORT)) {
            dropMenu.push(
                <Menu.Item key={BUTTON.EXCEL_EXPORT} onClick={excelExport}>
                    Excel导出
                </Menu.Item>
            );
        }

        return dropMenu;
    }, [HasRight, updateData, postponeNextMonth, excelExport]);


    return (
        <Search.Wrapper onSearch={searchHandle}>
            <TwoColHead
                rightStyle={{ justifyContent: 'flex-start' }}
                left={
                    <Search.Commonly>
                        <Search.Item label="机构">
                            <OrganizationSelect
                                isStrictly
                                allowClear={false}
                                isNeedPermission
                                style={{ width: 220 }}
                                value={organizationCode}
                                treeDataFromProp
                                treeDataList={organizationList}
                                onChange={handleOrgChange}
                                unLoading
                            />
                        </Search.Item>
                        <Search.Item>
                            <OrganizationSelect
                                isStrictly
                                isFunctional
                                style={{ width: 150 }}
                                value={departmentCode}
                                onChange={handleDepChange}
                                extraQuery={{ auditStatus: 2 }}
                                unLoading
                            />
                        </Search.Item>
                        <Search.Item label="月份">
                            <MonthPicker
                                onChange={onChange}
                                value={periodMoment}
                                style={{ width: '110px' }}
                                allowClear={false}
                            />
                        </Search.Item>
                    </Search.Commonly>
                }
                right={
                    <TwoColHead
                        style={{ margin: 0, width: '100%' }}
                        left={
                            <>
                                <HasRight code={BUTTON.APPLY_PAYMENT}>
                                    <Button onClick={applyPayment}>申请付款</Button>
                                </HasRight>
                                <HasRight code={BUTTON.SEND_SALARY_PAYROLL}>
                                    <Button onClick={sendSalaryPayroll}>下发薪资单</Button>
                                </HasRight>
                                <HasRight code={BUTTON.APPROVE_SUBMIT}>
                                    <Button onClick={approveSubmit}>提交审批</Button>
                                </HasRight>
                                {/* <HasRight code={BUTTON.ITEM_CHECK_WARN}>
                                    <Button onClick={confirmItemRecheck}>提醒细项复核</Button>
                                    </HasRight> */}
                                <HasRight code={BUTTON.BATCH_APPROVE}>
                                    <Button type="primary" onClick={batchApprove}>
                                        批量通过
                                    </Button>
                                </HasRight>
                                {/* 财务批量 */}
                                <HasRight code={BUTTON.FN_BATCH_APPROVE}>
                                    <Button type="primary" onClick={batchApprove}>
                                        批量通过
                                    </Button>
                                </HasRight>
                                <HasRight code={BUTTON.OV_FINAL_BATCH_REJECT}>
                                    <Button onClick={batchReject}>驳回</Button>
                                </HasRight>

                                <If condition={
                                    needShowButton(BUTTON.UPDATE_DATA) || needShowButton(BUTTON.FN_UPDATE_DATA)
                                }>
                                    <Button onClick={updateData}>
                                        更新数据
                                    </Button>
                                </If>
                            </>
                        }
                        right={
                            <AutoDivider>
                                {/* <BizIcon type="searchbar_modifyheader_icon_default" className={styles.font22} /> */}

                                <If condition={needShowButton(BUTTON.FN_SUBMIT_DETAIL)}>
                                    <Button type="link" onClick={goToSubmitDetail} style={{ padding: 0 }}>
                                        查看审批详情
                                    </Button>
                                </If>

                                <If condition={dropDownMenu.length > 0}>
                                    <Dropdown overlay={<Menu>{dropDownMenu}</Menu>} placement="bottomRight">
                                        <BizIcon type="listfunction_more_icon_default" className={styles.font22} />
                                    </Dropdown>
                                </If>
                            </AutoDivider>
                        }
                        addMarginInRightChild={false}
                    />
                }
            />
            <BaseMore form={form} searchModel={searchModel}>
                <Search.Item label="HR复核状态">
                    {getFieldDecorator('hrCheckStatus', {
                        initialValue: ''
                    })(
                        <Select>
                            <Select.Option value="">全部</Select.Option>
                            {hrCheckList.map(item => (
                                <Select.Option value={item.key} key={item.key}>
                                    {item.value}
                                </Select.Option>
                            ))}
                        </Select>
                    )}
                </Search.Item>
                <Search.Item label="财务复核状态">
                    {getFieldDecorator('financeCheckStatus', {
                        initialValue: ''
                    })(
                        <Select>
                            <Select.Option value="">全部</Select.Option>
                            {financeCheckList.map(item => (
                                <Select.Option value={item.key} key={item.key}>
                                    {item.value}
                                </Select.Option>
                            ))}
                        </Select>
                    )}
                </Search.Item>
            </BaseMore>
        </Search.Wrapper>
    );
};

export default memo(Form.create({})(CheckHeader));
